<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>智能化象差推理系统-数据概览</h1>
      <!-- <p>欢迎使用智能化象差推理系统，以下是您的数据概览</p> -->
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-header">
          <h3>应用统计</h3>
          <div class="stat-total">总数: {{ appStats.total || 0 }}</div>
        </div>
        <div class="chart-container">
          <div ref="appChartRef" class="chart"></div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <h3>设备统计</h3>
          <div class="stat-total">总数: {{ deviceStats.total || 0 }}</div>
        </div>
        <div class="chart-container">
          <div ref="deviceChartRef" class="chart"></div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <h3>物候期分布</h3>
          <div class="stat-total">总数: {{ phenologyStats.totalPhenology || 0 }}</div>
        </div>
        <div class="chart-container">
          <div ref="phenologyChartRef" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 预警记录区域 -->
    <div class="warning-section">
      <div class="section-header">
        <h3>最新预警记录</h3>
            <router-link to="/agricultureXctl/recognition" class="view-all">
  查看全部
</router-link>
      </div>
      <div class="warning-table-container">
        <table class="warning-table" v-if="warningRecords.length > 0">
          <thead>
            <tr>
              <!-- 记录ID 列已删除 -->
              <th>设备名称</th>
              <th>应用名称</th>
              <th>识别结果</th>
              <th>置信度</th>
              <th>创建时间</th>
              <!-- 查看详情操作已注释掉 -->
              <!-- <th>操作</th> -->
            </tr>
          </thead>
          <tbody>
            <tr v-for="record in warningRecords" :key="record.recordId">
              <!-- 不再展示 recordId -->
              <td>{{ getDeviceName(record.deviceId) }}</td>
              <td>{{ getAppName(record.appId) }}</td>
              <td>
                <div class="result-preview" v-if="record.recResult">
                  {{ formatRecResult(record.recResult) }}
                </div>
                <span v-else>无结果</span>
              </td>
              <td>
                <span class="confidence-tag" :class="getConfidenceClass(record.confidence)">
                  {{ record.confidence !== undefined && record.confidence !== null ? (parseFloat(record.confidence) * 100).toFixed(2) + '%' : '未知' }}
                </span>
              </td>
              <td>{{ formatDate(record.createTime) }}</td>
              <!-- 查看详情按钮已注释掉，若需要恢复请取消下面注释 -->
              <!--
              <td>
                <button class="action-btn" @click="viewDetail(record.recordId)">查看详情</button>
              </td>
              -->
            </tr>
          </tbody>
        </table>
        <div class="empty-data" v-else>
          <div class="empty-icon">📊</div>
          <p>暂无预警记录</p>
        </div>
      </div>
    </div>
    
    
    <!-- <div class="phenology-section">
      <div class="section-header">
        <h3>物候期展示</h3>
        <router-link to="/phenology/display" class="view-all">查看全部</router-link>
      </div>
      <div class="phenology-container">
        
        <div class="phenology-crops">
          <h4>作物列表</h4>
          <div class="crop-list">
            <div 
              v-for="crop in crops" 
              :key="crop.cropid"
              :class="['crop-item', { selected: selectedCrop?.cropid === crop.cropid }]"
              @click="selectCrop(crop)"
            >
              <div class="crop-info">
                <div class="crop-name">{{ crop.cropname }}</div>
                <div class="crop-desc">{{ crop.cropdescription }}</div>
              </div>
            </div>
            <div class="empty-data" v-if="crops.length === 0">
              <div class="empty-icon">🌱</div>
              <p>暂无作物数据</p>
            </div>
          </div>
        </div>
        
        
        <div class="phenology-periods" v-if="selectedCrop">
          <h4>{{ selectedCrop.cropname }}的物候期</h4>
          <div class="period-list">
            <div 
              v-for="period in cropPeriods" 
              :key="period.phenologicalperiodid"
              :class="['period-item', { selected: selectedPeriod?.phenologicalperiodid === period.phenologicalperiodid }]"
              @click="selectPeriod(period)"
            >
              <div class="period-info">
                <div class="period-name">{{ period.phenologicalperiodname }}</div>
                <div class="period-time">
                  {{ formatDate(period.starttime) }} - {{ formatDate(period.endtime) }}
                </div>
                <div class="period-characteristics">{{ period.characteristics }}</div>
              </div>
            </div>
            <div class="empty-data" v-if="cropPeriods.length === 0">
              <div class="empty-icon">🌿</div>
              <p>暂无物候期数据</p>
            </div>
          </div>
        </div>
        
        
        <div class="phenology-guidances" v-if="selectedPeriod">
          <h4>{{ selectedPeriod.phenologicalperiodname }}的指导信息</h4>
          <div class="guidance-list">
            <div 
              v-for="guidance in periodGuidances" 
              :key="guidance.guidanceid"
              class="guidance-item"
            >
              <div class="guidance-info">
                <div class="guidance-header">
                  <div class="guidance-name">{{ guidance.guidancename }}</div>
                  <div class="guidance-type">{{ guidance.guidetype }}</div>
                </div>
                <div class="guidance-period">周期：{{ guidance.guidanceperiod }}</div>
                <div class="guidance-implementation">{{ guidance.standardizedImplementation }}</div>
              </div>
            </div>
            <div class="empty-data" v-if="periodGuidances.length === 0">
              <div class="empty-icon">📋</div>
              <p>暂无指导信息</p>
            </div>
          </div>
        </div>
      </div>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
// 修正API导入路径（你的原始路径我保留）
import dashboardAPI from '@/api/agriculture/xctl/dashboard'
import appAPI from '@/api/agriculture/xctl/appManage'
import deviceAPI from '@/api/agriculture/xctl/device'
// 物候期相关API
import { listCrops } from '@/api/agriculture/xctl/crops'
import { listPhenologicalperiods } from '@/api/agriculture/xctl/phenologicalperiods'
import { listPhenologicalguidance } from '@/api/agriculture/xctl/phenologicalguidance'

const router = useRouter()

// 图表引用
const appChartRef = ref(null)
const deviceChartRef = ref(null)
const phenologyChartRef = ref(null)

// 数据状态
const appStats = ref({ total: 0, statusDistribution: {}, typeDistribution: {} })
const deviceStats = ref({ total: 0, statusDistribution: {} })
const phenologyStats = ref({ totalPhenology: 0, cropDistribution: {} })
const warningRecords = ref([])

// 物候期相关数据
const crops = ref([])
const periods = ref([])
const guidances = ref([])
const selectedCrop = ref(null)
const selectedPeriod = ref(null)

// 物候期计算属性
const cropPeriods = computed(() => {
  if (!selectedCrop.value) return []
  return periods.value.filter(period => period.cropid === selectedCrop.value.cropid)
})

const periodGuidances = computed(() => {
  if (!selectedPeriod.value) return []
  return guidances.value.filter(guidance => guidance.phenologicalperiodid === selectedPeriod.value.phenologicalperiodid)
})

// 图表实例
let appChart = null
let deviceChart = null
let phenologyChart = null

// 设备和应用数据缓存（映射）
const deviceMap = ref({})
const appMap = ref({})

// 统一页面 resize handler（只绑定一次）
const resizeHandler = () => {
  if (appChart) appChart.resize()
  if (deviceChart) deviceChart.resize()
  if (phenologyChart) phenologyChart.resize()
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await dashboardAPI.getStats()
    if (res.code === 200) {
      appStats.value = res.data.appStats || { total: 0, statusDistribution: {}, typeDistribution: {} }
      deviceStats.value = res.data.deviceStats || { total: 0, statusDistribution: {} }
      // 直接初始化图表（数据更新时也能刷新）
      nextTick(() => {
        initAppChart()
        initDeviceChart()
      })
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取物候期数据
const fetchPhenologyData = async () => {
  try {
    const res = await dashboardAPI.getPhenologyData()
    if (res.code === 200) {
      phenologyStats.value = res.data || { totalPhenology: 0, cropDistribution: {} }
      nextTick(() => {
        initPhenologyChart()
      })
    }
  } catch (error) {
    console.error('获取物候期数据失败:', error)
  }
}

// 获取最新预警记录
const fetchLatestWarnings = async () => {
  try {
    const res = await dashboardAPI.getLatestWarnings()
    if (res.code === 200) {
      warningRecords.value = res.rows || []
      // 获取相关的设备和应用信息以显示名称
      await fetchDevicesAndApps()
    }
  } catch (error) {
    console.error('获取预警记录失败:', error)
  }
}

// 获取设备和应用数据，并填充映射（兼容字符串/数字）
const fetchDevicesAndApps = async () => {
  try {
    const deviceRes = await deviceAPI.getDeviceList()
    if (deviceRes.code === 200 && deviceRes.rows) {
      deviceRes.rows.forEach(device => {
        const id = device.deviceId
        deviceMap.value[id] = device
        deviceMap.value[String(id)] = device
        const numId = Number(id)
        if (!isNaN(numId)) deviceMap.value[numId] = device
      })
    }
    
    const appRes = await appAPI.getAppList()
    if (appRes.code === 200 && appRes.rows) {
      appRes.rows.forEach(app => {
        const id = app.appId
        appMap.value[id] = app
        appMap.value[String(id)] = app
        const numId = Number(id)
        if (!isNaN(numId)) appMap.value[numId] = app
      })
    }
  } catch (error) {
    console.error('获取设备和应用数据失败:', error)
  }
}

// 获取设备名称（不回退到显示 ID）
const getDeviceName = (deviceId) => {
  if (deviceId === null || deviceId === undefined) return '未知设备'
  const d = deviceMap.value[deviceId] || deviceMap.value[String(deviceId)] || deviceMap.value[Number(deviceId)]
  return d?.deviceName || '未知设备'
}

// 获取应用名称（不回退到显示 ID）
const getAppName = (appId) => {
  if (appId === null || appId === undefined) return '未知应用'
  const a = appMap.value[appId] || appMap.value[String(appId)] || appMap.value[Number(appId)]
  return a?.appName || '未知应用'
}

// 格式化识别结果：解析 JSON 并返回 “病害 (置信度%)” 格式；若有多个 detection 以 ; 分隔
const formatRecResult = (recResult) => {
  if (!recResult) return '无结果'
  try {
    const result = typeof recResult === 'string' ? JSON.parse(recResult) : recResult
    // 优先处理 detections 数组
    if (result.detections && Array.isArray(result.detections) && result.detections.length > 0) {
      const parts = result.detections.map(detection => {
        const cls = detection.class || detection.label || '未知'
        const conf = detection.confidence !== undefined && detection.confidence !== null
          ? (parseFloat(detection.confidence) * 100).toFixed(2) + '%'
          : '未知'
        return `${cls} (${conf})`
      })
      return parts.join('; ')
    }
    // 兼容其它可能字段
    if (result.label || result.name) {
      const cls = result.label || result.name
      const conf = result.confidence !== undefined && result.confidence !== null
        ? (parseFloat(result.confidence) * 100).toFixed(2) + '%'
        : null
      return conf ? `${cls} (${conf})` : cls
    }
    return '无检测结果'
  } catch (e) {
    // 不是 JSON，回退为文本展示（截断）
    const s = String(recResult || '')
    return s.length > 60 ? s.substring(0, 60) + '...' : s
  }
}

// 获取置信度样式类
const getConfidenceClass = (confidence) => {
  if (confidence === undefined || confidence === null) return 'confidence-unknown'
  const value = parseFloat(confidence)
  if (!isFinite(value)) return 'confidence-unknown'
  if (value >= 0.8) return 'confidence-high'
  if (value >= 0.5) return 'confidence-medium'
  return 'confidence-low'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) return dateStr
  return date.toLocaleString()
}

/* -------------------------
   ECharts 初始化（改为柱状图）
   ------------------------- */

// 初始化应用状态柱状图（包含状态与类型两个 series）
const initAppChart = () => {
  if (!appChartRef.value) return
  if (appChart) appChart.dispose()
  appChart = echarts.init(appChartRef.value)

  const statusData = appStats.value.statusDistribution || {}
  const typeData = appStats.value.typeDistribution || {}

  const mapStatusName = (k) => (k === '0' ? '正常' : k === '1' ? '停用' : String(k))
  const statusEntries = Object.entries(statusData).map(([k, v]) => [mapStatusName(k), v])
  const typeEntries = Object.entries(typeData).map(([k, v]) => [String(k), v])

  // X轴类别顺序：状态在前，类型在后
  const categories = [...statusEntries.map(e => e[0]), ...typeEntries.map(e => e[0])]

  // 状态 series：只在状态位置显示值，其余填 null
  const statusSeriesData = categories.map(cat => {
    const found = statusEntries.find(e => e[0] === cat)
    return found ? found[1] : null
  })

  // 类型 series：只在类型位置显示值，其余填 null
  const typeSeriesData = categories.map(cat => {
    const found = typeEntries.find(e => e[0] === cat)
    return found ? found[1] : null
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) =>
        params
          .map(p => p.value !== null ? `${p.seriesName}: ${p.value}` : '')
          .filter(Boolean)
          .join('<br/>')
    },
    legend: { top: 8, data: ['应用状态', '应用类型'] },
    grid: { left: '3%', right: '4%', bottom: '6%', containLabel: true },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: { interval: 0 }
    },
    yAxis: {
      type: 'value',
      axisLabel: { show: false },
      splitLine: { show: false }
    },
    series: [
      {
        name: '应用状态',
        type: 'bar',
        data: statusSeriesData,
        label: { show: true, position: 'top' },
        barWidth: 30,
        barGap: 0,           // 与另一系列并排显示
        barCategoryGap: '40%' // 同类别柱子之间间距
      },
      {
        name: '应用类型',
        type: 'bar',
        data: typeSeriesData,
        label: { show: true, position: 'top' },
        barWidth: 30,
        barGap: 0,
        barCategoryGap: '40%'
      }
    ]
  }

  appChart.setOption(option)
}



// 初始化设备状态柱状图
const initDeviceChart = () => {
  if (!deviceChartRef.value) return
  if (deviceChart) deviceChart.dispose()
  deviceChart = echarts.init(deviceChartRef.value)

  const statusData = deviceStats.value.statusDistribution || {}
  const mapStatusName = (k) => (k === '0' ? '正常' : k === '1' ? '异常' : String(k))
  const entries = Object.entries(statusData).map(([k, v]) => [mapStatusName(k), v])
  const categories = entries.map(e => e[0])
  const values = entries.map(e => e[1])

  const option = {
    tooltip: {
      trigger: 'item', // 改为 item，显示单柱信息
      formatter: (params) => `${params.name}: ${params.value}`
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: { interval: 0 },
      axisTick: { alignWithLabel: true }
    },
    yAxis: {
      type: 'value',
      axisLabel: { show: false },
      splitLine: { show: false }
    },
    series: [
      {
        name: '设备数量',
        type: 'bar',
        data: values,
        label: { show: true, position: 'top' },
        barWidth: 40,
        emphasis: { focus: 'series' }
      }
    ],
    grid: { left: '3%', right: '4%', bottom: '6%', containLabel: true }
  }

  deviceChart.setOption(option)
}


// 初始化物候期分布柱状图
const initPhenologyChart = () => {
  if (!phenologyChartRef.value) return
  if (phenologyChart) phenologyChart.dispose()
  phenologyChart = echarts.init(phenologyChartRef.value)

  const cropData = phenologyStats.value.cropDistribution || {}
  const entries = Object.entries(cropData).map(([k, v]) => [String(k), v])
  const categories = entries.map(e => e[0])
  const values = entries.map(e => e[1])

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => params.map(p => p.seriesName).join('<br/>')
    },
    legend: { top: 8, data: ['物候期数量'] },
    grid: { left: '3%', right: '4%', bottom: '6%', containLabel: true },
    xAxis: { type: 'category', data: categories, axisLabel: { rotate: categories.length > 8 ? 30 : 0, interval: 0 } },
    yAxis: { show: false },
    series: [
      {
        name: '物候期数量',
        type: 'bar',
        data: values,
        barWidth: 20,
        label: { show: true, position: 'top' },
        emphasis: { focus: 'series' }
      }
    ]
  }

  phenologyChart.setOption(option)
}
/* -------------------------
   物候期相关方法与数据加载
   ------------------------- */

const selectCrop = (crop) => {
  selectedCrop.value = crop
  selectedPeriod.value = null
  loadPeriods(crop.cropid)
}

const selectPeriod = (period) => {
  selectedPeriod.value = period
  loadGuidances(period.phenologicalperiodid)
}

const loadCrops = async () => {
  try {
    const response = await listCrops({})
    crops.value = response.rows || []
  } catch (error) {
    console.error('加载作物数据失败:', error)
  }
}

const loadPeriods = async (cropId) => {
  try {
    const response = await listPhenologicalperiods({ cropid: cropId })
    periods.value = response.rows || []
  } catch (error) {
    console.error('加载物候期数据失败:', error)
  }
}

const loadGuidances = async (periodId) => {
  try {
    const response = await listPhenologicalguidance({ phenologicalperiodid: periodId })
    guidances.value = response.rows || []
  } catch (error) {
    console.error('加载指导信息失败:', error)
  }
}

/*  查看详情函数已注释掉；如果你想恢复查看详情功能，取消注释并恢复模板中的按钮
const viewDetail = (id) => {
  router.push(`/recognition-records?id=${id}`)
}
*/

onMounted(async () => {
  // 拉取多项数据
  await Promise.all([
    fetchStats(),
    fetchPhenologyData(),
    fetchLatestWarnings(),
    fetchDevicesAndApps(),
    loadCrops()
  ])

  // 初始化图表（确保 DOM 已渲染）
  nextTick(() => {
    initAppChart()
    initDeviceChart()
    initPhenologyChart()
  })

  // 绑定一次 resize 事件，组件卸载时移除
  window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler)
  if (appChart) { appChart.dispose(); appChart = null }
  if (deviceChart) { deviceChart.dispose(); deviceChart = null }
  if (phenologyChart) { phenologyChart.dispose(); phenologyChart = null }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #1a202c;
  margin: 0 0 8px 0;
}

.dashboard-header p {
  font-size: 16px;
  color: #718096;
  margin: 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stat-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  margin: 0;
}

.stat-total {
  font-size: 16px;
  font-weight: 500;
  color: #4299e1;
}

.chart-container {
  height: 250px;
}

.chart {
  width: 100%;
  height: 100%;
}

.warning-section, .phenology-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  margin: 0;
}

.view-all {
  color: #4299e1;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
}

.warning-table-container {
  overflow-x: auto;
}

.warning-table {
  width: 100%;
  border-collapse: collapse;
}

.warning-table th {
  background-color: #f7fafc;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #4a5568;
  font-size: 14px;
}

.warning-table td {
  padding: 12px 16px;
  border-top: 1px solid #edf2f7;
  color: #2d3748;
  font-size: 14px;
}

.warning-table tr:hover {
  background-color: #f7fafc;
}

.warning-tag {
  display: inline-block;
  padding: 4px 8px;
  background-color: #fed7d7;
  color: #e53e3e;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.result-preview {
  max-width: 320px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.confidence-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
}

.confidence-high {
  background-color: #52c41a;
  color: white;
}

.confidence-medium {
  background-color: #faad14;
  color: white;
}

.confidence-low {
  background-color: #ff4d4f;
  color: white;
}

.confidence-unknown {
  background-color: #d9d9d9;
  color: #666;
}

.action-btn {
  background-color: #ebf8ff;
  color: #3182ce;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.action-btn:hover {
  background-color: #bee3f8;
}

.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #a0aec0;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-data p {
  font-size: 16px;
  margin: 0;
}

/* 物候期展示样式 */
.phenology-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.phenology-crops, .phenology-periods, .phenology-guidances {
  background-color: #f7fafc;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.phenology-crops h4, .phenology-periods h4, .phenology-guidances h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #2d3748;
  font-size: 16px;
  border-bottom: 1px solid #edf2f7;
  padding-bottom: 10px;
}

.crop-list, .period-list, .guidance-list {
  max-height: 300px;
  overflow-y: auto;
}

.crop-item, .period-item, .guidance-item {
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 10px;
  background-color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #edf2f7;
}

.crop-item:hover, .period-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.crop-item.selected, .period-item.selected {
  border-color: #4299e1;
  background-color: #ebf8ff;
}

.crop-name, .period-name, .guidance-name {
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 5px;
}

.crop-desc, .period-characteristics, .guidance-implementation {
  font-size: 13px;
  color: #4a5568;
  margin-top: 5px;
}

.period-time, .guidance-period {
  font-size: 12px;
  color: #718096;
  margin-top: 5px;
}

.guidance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.guidance-type {
  font-size: 12px;
  background-color: #e6fffa;
  color: #38b2ac;
  padding: 2px 6px;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    padding: 16px;
  }
  
  .chart-container {
    height: 200px;
  }
  
  .warning-table th,
  .warning-table td {
    padding: 8px 12px;
    font-size: 13px;
  }
  
  .phenology-container {
    grid-template-columns: 1fr;
  }
}
</style>
